<template>
	<view class="content">
		<view class="header" :style="{backgroundColor:`rgba(231, 231, 231,${transparency})`}">
			<view class="" :style="{height: statusbarHeight+'px'}">
			</view>
			<view class="flex">
				<view class="round" @click="getback" :style="{backgroundColor:`rgba(231, 231, 231,${1-transparency})`}">
					<uni-icons size="24" type="arrowleft" />
				</view>
				<view class="nav">
					<view class="navitem" v-for="(item,index) in nav_list" :key=index @click="changNavId(item)" :style="{color:nav_id!=item.id ? `rgba(25, 25, 25,${transparency})` 
					: `rgba(0, 108, 265,${transparency})`  }">
						{{item.text}}
					</view>
				</view>
				<view class="round">
				</view>
			</view>
		</view>
		<scroll-view scroll-y=true style="height: 100vh;" @scroll="scroll" :scroll-top="scrollTop"
			:scroll-into-view="scrollId" scroll-with-animation="true">
			<!-- 商品 -->
			<view class="commodity">
				<swiper class="swiper" indicator-color="#ffffff" indicator-active-color="#ff0000" circular
					indicator-dots="true">
					<swiper-item v-for="(item,index) in list" :key="index">
						<image :src="item" mode=""></image>
					</swiper-item>
				</swiper>
			</view>
			<view class="base-info column">
				<text class="name">{{detail.title}}</text>
				<text class="title">{{detail.vipFree==1?'会员免费':'免费'}}</text>
				<view class="row space-between-algin align-height">
					<view class="location">
						<text class="yzb yzb-ic_visibility_px"></text>
						<text class="city">{{detail.viewNumber}}</text>
					</view>
					<view class="location">
						<text class="yzb yzb-shijian"></text>
						<text class="city">{{detail.createTime}}</text>
					</view>
				</view>
			</view>
			<!-- 详情 -->
			<view class="nav-title">
				<text class="yzb yzb-x-"></text>
				<text class="title">详情介绍</text>
			</view>
			<view class="audio" v-if="showAudio">
				<y-audio ref="music" :music="detail.url" @onStatus="playStatus" :image="detail.cover"
					:title="detail.title" :autoplay="false"></y-audio>
			</view>
			<view class="details box" :id="'scrollView'+nav_list[0].id">
				<view class="column">
					<rich-text v-if="detail.detail" style="word-wrap: break-word;word-break: break-all;" space="nbsp"
						:nodes="detail.detail"></rich-text>
					<text v-else style="padding: 30upx 20upx;">无</text>
				</view>
			</view>
			<!-- 推荐 -->
			<view class="nav-title">
				<text class="yzb yzb-x-"></text>
				<text class="title">为您推荐</text>
			</view>
			<view class="recommend box2" :id="'scrollView'+nav_list[1].id">
				<train-list v-if="recommendList.length>0" :list="recommendList"></train-list>
				<m-empty-data v-else :coverUrl="no_order_1" noTxt="暂无记录"></m-empty-data>
			</view>
		</scroll-view>
		<view class="bottom"><uni-goods-nav :fill="true" :options="options" :button-group="customButtonGroup"
				@click="onClick" @buttonClick="buttonClick" /></view>
		<video v-if="video.visible" :src="video.url" id="videoPlayer"
			@fullscreenchange="onVideoFullScreenChange"></video>
		<!-- <view v-if="showAudio" class="music" :class="autoplay?'music-rot':''" @click="playMusic"><text
				class="yzb yzb-yinleyule"></text></view> -->
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations,
		mapGetters
	} from 'vuex'
	export default {
		computed: {
			...mapState(['userInfo']),
			...mapGetters(['hasLogin'])
		},
		data() {
			return {
				detail: {},
				no_order_1: this.$mAssetsPath.no_order_1,

				video: {
					visible: false,
					url: '',
					context: null
				},
				showAudio: false,
				autoplay: false,
				query: {
					page: 1,
					limit: 10,
				},

				list: ["https://picnew12.photophoto.cn/20180731/taobaohufupinlunboxuanchuanhaibao-30671462_1.jpg"],
				statusbarHeight: uni.getSystemInfoSync().statusBarHeight, //刘海屏高度
				scrollTop: 0, //设置竖向滚动条位置
				nav_list: [{
						id: 1,
						text: '详情',
						scrollId: "scrollView1"
					},
					{
						id: 2,
						text: '推荐',
						scrollId: "scrollView3"
					}
				],
				nav_id: null, //导航选中id
				scrollId: "",
				transparency: 0, //透明度
				isDropDown: false, //下拉到临界点
				//临界值(图片高度-头部高度-刘海屏高度 250-50-刘海屏高度) 
				criticalValue: 200 - uni.getSystemInfoSync().statusBarHeight,

				recommendList: [],

				options: [{
						icon: 'home',
						text: '首页',
						color: '#646566'
					},
					// {
					// 	icon: 'redo',
					// 	text: '分享',
					// 	color: '#646566'
					// },
				],
				customButtonGroup: [{
					text: '预览资源',
					backgroundColor: 'linear-gradient(90deg, #1E83FF, #12ae85)',
					color: '#fff'
				}, ],
			}
		},
		// //页面滚动触发
		// onPageScroll(e) {
		// 	this.transparency = e.scrollTop/this.criticalValue
		// 	if(!this.isDropDown && e.scrollTop >=this.criticalValue){
		// 		this.isDropDown = true
		// 	}else if(this.isDropDown && e.scrollTop <this.criticalValue){
		// 		this.isDropDown = false

		// 	}
		// },

		onReachBottom() {
			console.log("onReachBottom");
			this.getRecommendList("add");
		},

		onLoad(options) {
			this.getDetail(options.id);
		},

		onReady() {
			this.video.context = uni.createVideoContext('videoPlayer', this);
		},
		
		onShow() {
			console.log("onShow===",this.userInfo);
			if(this.detail.vipFree==1){
				this.updateState();
			}
		},

		methods: {
			...mapMutations(['SET_ACTIVE']),
			/**
			 * 查询详情
			 */
			async getDetail(id) {
				uni.showLoading({
					mask: true
				});
				let res = await this.$apis.getTrainFileDetail({
					id: id
				});
				console.log('res====', res);
				if (res) {
					if (res.album) {
						this.list = res.album.split(',');
					}
					this.detail = res;
					this.getRecommendList();
					if(this.detail.vipFree==1 ){
						this.updateState();
					}
					
				}
				uni.hideLoading();
			},
			
			updateState(){
				//vip才能查看
				if(this.userInfo.vipLevel>0){
					//当前会员
					this.customButtonGroup[0].text="预览资源";
					this.customButtonGroup[0].backgroundColor="linear-gradient(90deg, #1E83FF, #12ae85)";
				}else{
					this.customButtonGroup[0].text="会员解锁";
					this.customButtonGroup[0].backgroundColor="linear-gradient(90deg, #f0ad4e, #FE6035)";
				}
			},

			getRecommendList(type = 'refresh') {
				if (type == 'refresh') {
					this.query.page = 1;
				} else {
					this.query.page++;
				}
				this.$apis.getTrainList(this.query).then(res => {
					console.log("===getTrainList=====", res);
					if (this.query.page == 1) {
						this.recommendList = []; //如果是第一页需手动制空列表
					}
					this.recommendList = this.recommendList.concat(res.records); //追加新数据
				}).catch(() => {
					//联网失败, 结束加载
				})
			},

			preview() {
				if(!this.hasLogin){
					this.$mRouter.push({
						route: this.$mRoutesConfig.login
					});
					return;
				}
				//判断文件类型
				if (this.detail.fileType == "audio") {
					this.playMusic();
				} else if (this.detail.fileType == "video") {
					this.playVideo();
				} else {
					this.online_preview();
				}
			},

			playMusic() {
				console.log("===playMusic===", this.$refs.music);
				this.showAudio = true;
				setTimeout(() => {
					console.log("开始播放")
					this.$refs.music.clickAudio();
				}, 300)
			},

			playStatus(status) {
				console.log("playStatus", status);
				if (status == 1) {
					this.audoPlay = true;
				} else {
					this.audoPlay = false;
				}
			},

			playVideo() {
				this.video.visible = true;
				this.video.url = this.detail.url;
				this.$nextTick(() => {
					this.video.context.requestFullScreen({
						direction: 0
					});
					this.video.context.play();
				});
			},
			onVideoFullScreenChange(e) {
				//当退出全屏播放时，隐藏播放器
				if (this.video.visible && !e.detail.fullScreen) {
					this.video.visible = false;
					this.video.context.stop();
				}
			},

			//在线预览文档  
			online_preview() {
				//#ifndef H5  
				uni.showLoading({
					title: '加载中...'
				}) //出现加载中图标  
				let str = this.detail.url
				uni.downloadFile({
					url: str, //要预览的PDF的地址  
					success: function(res) {
						console.log('预览成功', res)

						if (res.statusCode === 200) {
							var Path = res.tempFilePath //返回的文件临时地址，用于后面打开本地预览所用  
							uni.openDocument({
								filePath: Path, //要打开的文件路径  
								showMenu: false, //右上角是否有可以转发分享的功能  
								success: function(res) {
									uni.hideLoading() //关闭加载中图标  
									uni.showToast({
										title: '打开成功',
										icon: 'none'
									})
								},
								fail: function(res) {
									uni.hideLoading() //关闭加载中图标  
									uni.showToast({
										title: '打开失败,请下载wps再试',
										icon: 'none'
									})
									console.log('打开失败', res) //打开失败  
								}
							})
						}
					},
					fail: function(res) {
						uni.hideLoading() //关闭加载中图标  
						uni.showToast({
							title: '加载失败,请稍后再试',
							icon: 'none'
						})
						console.log('加载失败', res) //预览失败  
					}
				})
				// #endif  
				//#ifdef H5   
				let resultNew = encodeURIComponent(this.detail.url)
				this.allUrl2 = 'http://view.officeapps.live.com/op/view.aspx?src=' + resultNew
				window.open(this.detail.url);
				// window.open(this.allUrl2)
				// #endif  
			},

			//scroll-view滚动触发
			scroll(e) {
				const scrollTop = e.detail.scrollTop
				this.calcSize()
				const tabs = this.nav_list.filter(item => item.top <= scrollTop).reverse();
				if (tabs.length > 0) {
					this.nav_id = tabs[0].id;
				}
				this.transparency = e.detail.scrollTop / this.criticalValue
				if (!this.isDropDown && e.detail.scrollTop >= this.criticalValue) {
					this.isDropDown = true
				} else if (this.isDropDown && e.detail.scrollTop < this.criticalValue) {
					this.isDropDown = false
					this.nav_id = null
				}
			},
			//计算高度
			calcSize(event) {
				let h = 0;
				this.nav_list.forEach(item => {
					let view = uni.createSelectorQuery().select(`#${item.scrollId}`);
					view.fields({
						size: true
					}, data => {
						if (data != null) {
							//加上图片高度 -(header+刘海屏)高度 +margin高度
							item.top = h + 250 - 50 - uni.getSystemInfoSync().statusBarHeight + 10 * item
								.id;
							h += data.height
							item.bottom = h;
						}

					}).exec();
				})

			},
			//点击头部标题
			changNavId(item) {
				if (!this.isDropDown) return
				this.nav_id = item.id
				//scroll-into-view滚动到指定view会有头部高度的误差 用scroll-top来取代
				// this.scrollId = item.scrollId
				this.nav_list.forEach(n => {
					if (n.id == item.id) {
						this.scrollTop = String(item.top)
					}

				})
			},
			//返回
			getback() {
				uni.navigateBack()
			},
			//分享
			share() {
				uni.showToast({
					title: '分享',
					icon: 'none',
					duration: 2000
				})
			},

			onClick(e) {
				console.log("==onClick===", e);
				if (e.index == 0) {
					//首页
					this.SET_ACTIVE("home")
					this.$mRouter.switchTab({
						route: this.$mRoutesConfig.index,
					});
				} else if (e.index == 1) {}
			},

			buttonClick(val) {
				if(!this.hasLogin){
					this.$mRouter.push({
						route: this.$mRoutesConfig.login
					});
					return;
				}
				if(val.content.text=='会员解锁'){
					uni.navigateTo({
						url:'/pages/user/vip/vip'
					})
				}else{
					this.preview();
				}
			},
		}

	}
</script>
<style>
	page {
		background-color: #f8f8f8;
	}
</style>
<style lang="scss" scoped>
	.content {
		padding-bottom: 100upx;
	}

	.header {

		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 99;

		.flex {
			align-items: center;
			display: flex;
			justify-content: space-between;
			padding: 0 20rpx;
			width: 100%;
			height: 100rpx;

		}

		.nav {
			display: flex;
			align-items: center;

			.navitem {
				margin-left: 30px;
				font-size: 30rpx;
			}

			.navitem:first-child {
				margin-left: 0;
			}
		}

		.round {
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 50%;

			width: 70rpx;
			height: 70rpx;
		}
	}

	.commodity {
		width: 100%;
		height: 500rpx;
		position: relative;

		.swiper {
			width: 100%;
			height: 500rpx;
		}

		image {
			width: 100%;
			height: 500rpx;

		}

		.assure {
			border-top-left-radius: 20upx;
			border-top-right-radius: 20upx;
			bottom: -60upx;
			position: absolute;
			width: 100%;
			padding: 10upx;
			align-items: center;
			display: flex;
			justify-content: center;
			background: rgba(232, 233, 253, 1);

			.yzb {
				color: #6B84E5;
			}

			.assure-info {
				color: #6B84E5;
			}
		}
	}

	.box {
		// margin-top: 20rpx;
		width: calc(100% - 20rpx);
		margin-left: 10rpx;
		border-radius: 20rpx;
		background-color: #fff;
		padding: 20rpx;
		// height: 1000px;
		box-sizing: border-box;
	}

	.box2 {
		// margin-top: 20rpx;
		width: calc(100% - 20rpx);
		margin-left: 10rpx;
		border-radius: 20rpx;
		background-color: #fff;
		// height: 1000px;
		box-sizing: border-box;
	}

	.base-info {
		background-color: #fff;
		box-sizing: border-box;
		padding: 20upx;

		.name {
			font-weight: bold;
			font-size: 34upx;
		}

		.title {
			font-size: 26upx;
			color: #666;
			padding: 10upx 0;
		}

		.location {
			text {
				color: #999;
				font-size: 24upx;
			}

			.city {
				margin-left: 10upx;
			}
		}
	}


	.nav-title {
		padding: 15upx;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;

		.yzb {
			font-size: 36upx;
			color: #666;
			margin-right: 10upx;
		}

		.title {
			text-align: center;
			font-weight: bold;
			font-size: 32upx;
		}
	}

	.details {

		padding-bottom: 100upx;

		.details-title {
			font-weight: bold;
			font-size: 34upx;
			padding: 20upx 0 10upx 0;
		}

		.details-content {
			font-weight: 28upx;
			color: #666;
		}
	}

	.recommend {}

	.audio {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 30upx 0;
		background-color: #fff;

		audio {
			width: 94%;
		}
	}

	@keyframes rot {
		0% {
			transform: rotate(0deg);
		}

		25% {
			transform: rotate(90deg);
		}

		50% {
			transform: rotate(180deg);
		}

		75% {
			transform: rotate(270deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.music {
		position: fixed;
		right: 30upx;
		top: 330upx;
		z-index: 99;

		text {
			background-color: #fff;
			font-size: 80upx;
			color: #007aff;
			border-radius: 40upx;
		}
	}

	.music-rot {
		animation: rot 2s linear infinite;
	}

	.bottom {
		position: fixed;
		bottom: 0;
		width: 100%;
		padding: 10upx 0;
		background-color: $bgcolor_white;
		border-top: 1upx solid $border-color-base;
	}
</style>